CODE 120. Container With Most Water

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/10/2013-11-10-CODE 120 Container With Most Water/

访问原文「CODE 120. Container With Most Water

Given n non-negative integers a1, a2,
…, an, where each represents a point at coordinate (i, ai). n vertical
lines are drawn such that the two endpoints of line i is at (i, ai)
and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public int maxArea(int[] height) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == height || height.length <= 0) {
return 0;
}
int max = Integer.MIN_VALUE;
for (int i = 0; i < height.length; i++) {
for (int j = 0; j < i; j++) {
if (height[j] >= height[i]) {
int tmp = (i - j) * height[i];
if (tmp > max) {
max = tmp;
}
break;
}
}
for (int j = height.length - 1; j > i; j--) {
if (height[j] >= height[i]) {
int tmp = (j - i) * height[i];
if (tmp > max) {
max = tmp;
}
break;
}
}
}
return max;
}
Jerky Lu wechat
欢迎加入微信公众号